package com.ximu.message;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;

public class MessageImp {

	public List<MessageBean> getAll(){
		DB db = new DB();
		List<MessageBean> all = new ArrayList<MessageBean>();
		try {
			ResultSet rs = db.query("SELECT * FROM message");
			while(rs.next()){
				MessageBean mb = new MessageBean();
				mb.setId(rs.getInt("id"));
				mb.setContents(rs.getString("contents"));
				mb.setUser(rs.getString("username"));
				mb.setTime(rs.getInt("time"));
				mb.setIp(rs.getInt("ip"));
				all.add(mb);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return all;
	}
	
	public int save(){
		HttpServletRequest request = ServletActionContext.getRequest();
		String user = request.getParameter("user");
		String contents = request.getParameter("contents");
		DB db = new DB();
		StringBuffer sql = new StringBuffer();
		sql.append("INSERT INTO message (`pid`,`time`,`username`,`contents`) VALUES ('0',UNIX_TIMESTAMP(),");
		sql.append("'"+user+"',");
		sql.append("'"+contents+"')");
		try{
			System.out.println(sql);
			return db.update(sql.toString());
		}catch(SQLException e){
			System.out.println(e.getMessage());
			return -1;
		}
	}
	
	public int del(){
		HttpServletRequest request = (HttpServletRequest)ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		String id = request.getParameter("id");
		DB db = new DB();
		StringBuffer sql = new StringBuffer();
		sql.append("DELETE FROM message WHERE id = ");
		sql.append(id);
		try{
			return db.update(sql.toString());
		}catch(SQLException e){
			return -1;
		}
	}
}
